﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HRProject.Code.DAO;
using HRProject.Code.Common;
using HRProject.Code.DTO;
using System.IO;

namespace HRProject.Department
{
    public partial class AddDepartment : System.Web.UI.Page
    {
        private Guid parentDeptId = Guid.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            string parentId = Request.Params["parentId"];
            try
            {
                parentDeptId = new Guid(parentId);
            }
            catch (Exception exp)
            {
                Console.Out.Write(exp.StackTrace);
                parentDeptId = Guid.Empty;
            }
            string parentName = Request.Params["parentName"];
            tbxParent.Text = parentName;
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            if (!BLAuthentication.IsAddAllowed)
            {
                lblError.Text = ContentProvider.GetMessage("NotAuthorized");
                return;
            }

            BLDepartment department = new BLDepartment();
            BLDepartment parent = new BLDepartment();
            department.Name = tbxName.Text;
            parent.Id = parentDeptId;
            department.Parent = parent;
            department.Description = txaDescription.Text;
            department.DataSignature = 0;

            string iconUrl = string.Empty;
            if (cbxIcon.Checked && fulIcon.HasFile)
            {
                try
                {
                    string ext = fulIcon.PostedFile.FileName.Substring(fulIcon.PostedFile.FileName.LastIndexOf('.'));
                    iconUrl = "/image/department/" + department.Name + ext;
                    fulIcon.PostedFile.SaveAs(Server.MapPath(iconUrl));
                    department.IconUrl = iconUrl;
                }
                catch (Exception ex)
                {
                    lblError.Text = "ERROR: " + ex.Message.ToString();
                }
            }
            else
            {
                lblError.Text = "You have not specified a file.";
            }

            DepartmentDAO dao = new DepartmentDAO();
            dao.insert(department);

            Util.CloseFrame(Response);
        }
    }
}
